#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/25 21:42
from time import sleep
from typing import List, Dict
import json

from selenium import webdriver
from msedge.selenium_tools import EdgeOptions
from msedge.selenium_tools import Edge

from config.config import config, ValueTypeEnum
from infrastructure.constants.request_method_enum import RequestMethodEnum


class SpiderUrl:
    def __init__(self, url:str, method:RequestMethodEnum=RequestMethodEnum.get):
        self.url:str = url
        self.method:RequestMethodEnum = method


class SeleniumSpider2JsonConfiguration:
    def __init__(self):
        self.option: Dict[str, object] = dict()
        self.arguments: List[str] = list()
        self.webdriver_path = config.get(section="selenium", key="webdriver")
        self.webdriver_type = config.get(section="selenium", key="webdriver_type")
        self.user_agent = config.get(section="selenium", key="user_agent")
        self.per_url_sleep_time = config.get(section="selenium", key="per_url_sleep_time", value_type=ValueTypeEnum.INT)
        self.prepose_urls: List[SpiderUrl] = list()
        self.data_url: SpiderUrl = None

    def add_prepose_url(self, url: str, method: RequestMethodEnum=RequestMethodEnum.get):
        self.prepose_urls.append(SpiderUrl(url, method))

    def set_data_url(self, url: str, method: RequestMethodEnum=RequestMethodEnum.get):
        self.data_url = SpiderUrl(url, method)

    def add_option(self, key: str, value):
        self.option[key] = value

    def add_arguments(self, argument: str):
        self.arguments.append(argument)


def spider2json(configuration: SeleniumSpider2JsonConfiguration):
    if not configuration:
        return None
    # 这里是用来隐藏弹出框的，如果没有这个，某查查会弹出提示框，会影响下一步操作
    option = EdgeOptions()
    option.use_chromium = True
    if configuration.option and len(configuration.option) > 0:
        for key, value in configuration.option:
            option.add_experimental_option(key, value)

    option.add_argument('--disable-gpu')

    # 使用浏览器开发者模式，配置实验性功能参数
    option.add_experimental_option('useAutomationExtension', False)
    option.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 这里使用无头浏览器，如果要观察整个操作流程，可以将此代码注释掉
    option.add_argument('--headless')
    option.add_argument('--no-sandbox')
    option.add_argument('--disable-dev-shm-usage')
    option.add_argument('user-agent=' + configuration.user_agent)

    # 设置无界面模式，也可以添加其它设置
    option.add_argument('headless')
    driver = Edge(executable_path=configuration.webdriver_path, options=option)

    if configuration.prepose_urls and len(configuration.prepose_urls) > 0:
        for url in configuration.prepose_urls:
            if url.method == RequestMethodEnum.get:
                driver.get(url.url)
                sleep(configuration.per_url_sleep_time)
    if configuration.data_url:
        if configuration.data_url.method == RequestMethodEnum.get:
            driver.get(configuration.data_url.url)
    return json.loads(driver.find_elements_by_tag_name("pre")[0].text)